import { defineStore } from 'pinia'

import { removeSingle, getCartList, renewCartList, updateItemFlag, updateListFlag } from '../services/index'

export const usePhongStore = defineStore('phong', {
  state() {
    return {
      token: localStorage.getItem('token') || '',
      cartList: []
    }
  },
  getters: {
    selectedCartList(state) {
      return state.cartList.filter(item => item.flag)
    }
  },
  actions: {
    setUserid(userid) {
      this.userid = userid
    },
    // 购物车列表
    async fetchCarList() {
      const { data } = await getCartList()
      if (data.data) {
        this.cartList = data.data
      } else {
        this.cartList = []
      }
    },
    // 购物车删除单个
    async removeCartItem(cartid) {
      const { data } = await removeSingle(cartid)
      if (data.code === '200') {
        const index = this.cartList.findIndex(item => item.cartid === cartid)
        this.cartList.splice(index, 1)
      }
    },
    // 更新数量
    async updateItemNum(cartid, num) {
      const { data } = await renewCartList(cartid, num)
      if (data.code === '200') {
        const index = this.cartList.findIndex(item => item.cartid === cartid)
        this.cartList[index].num = num
      }
    },
    // 修改 flag 是否选中
    async updateItemFlag(cartid, flag) {
      await updateItemFlag(cartid, flag)
    },
    // 全选
    async selectAll() {
      const { data } = await updateListFlag(true)
      if (data.code === '200') {
        this.cartList.forEach(item => (item.flag = true))
      }
    },
    // 全不选
    async deSelectAll() {
      const { data } = await updateListFlag(false)
      if (data.code === '200') {
        this.cartList.forEach(item => (item.flag = false))
      }
    }
  }
})
